package org.fullhappy.business;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.fullhappy.dao.MusicFacade;
import org.fullhappy.dao.MusicFileTypeFacade;
import org.fullhappy.entity.Music;
import org.fullhappy.entity.MusicFileType;
import org.fullhappy.model.MusicModel;

public class MusicSevice {

    private MusicFacade musicFacade;
    private MusicFileTypeFacade musicFileTypeFacade;

    public MusicSevice() {
        musicFacade = new MusicFacade();
        musicFileTypeFacade = new MusicFileTypeFacade();
    }

    public void create(Music music) throws Exception {
        music.setUserCreateId(1);
        music.setEnable((short) 1);
        music.setCreateTime(System.currentTimeMillis());
        musicFacade.create(music);
    }

    public int count() {
        return musicFacade.count();
    }

    public List<Music> findRange(int[] range) {
        return musicFacade.findRange(range);
    }

    public void edit(Music music) throws Exception {
        musicFacade.edit(music);
    }

    public void remove(Music music) throws Exception {
        musicFacade.remove(music);
    }

    public Object find(Integer key) {
        return musicFacade.find(key);
    }

    public void create(MusicModel musicModel) {
        Music music = new Music();
        
        music.setAuthorIds(musicModel.getAuthorIds());
        music.setCategoryId(musicModel.getCategoryId());
        
        music.setDescription(musicModel.getDescription());
        
        music.setSingerIds(musicModel.getSingerIds());        
        music.setTitle(musicModel.getTitle());
        music.setTypeId(0);
        music.setUserCreateId(musicModel.getUserCreateId());
        
        musicModel.saveAvatarImage();
        musicModel.saveSourceMusic();
        String musicFileName =  musicModel.getSourceMusic().getName();
        String avatarImageName = musicModel.getAvatarImage().getName();
        
        String ext = musicFileName.split("\\.")[musicFileName.split("\\.").length-1];
        MusicFileType musicFileType =  musicFileTypeFacade.findByExtensionOrCreateNewIfNotExist(ext);
        
        music.setSourceFile(musicFileName);
        music.setFileTypeId(musicFileType.getTypeId());
        music.setAvatarImageLink(avatarImageName); 
        
        try {
            create(music);
        } catch (Exception ex) {
            Logger.getLogger(MusicSevice.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
}
